<template>
  <div class="container">

    <!-- 左侧盒子 - 一周前时间数据 -->
    <div class="box">
      <h3 style="text-align: center; margin: 10px 0">一周前记录</h3>

      <!-- 左侧查询区域 -->
      <div class="card02"
        style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
        <el-input v-model="historyData.username" style="width: 200px; margin-right: 10px" placeholder="请输入姓名查询"
          disabled></el-input>
        <el-input v-model="historyData.realname" style="width: 200px; margin-right: 10px" placeholder="请选择类型查询"
          disabled></el-input>
        <el-button type="primary" @click="loadHistory">查询</el-button>
        <el-button type="info" style="margin: 0 10px" @click="resetHistory">重置</el-button>
      </div>

      <!-- 左侧数据表格区域 -->
      <div class="card"
        style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
        <el-table :data="historyData.tableData" stripe>
          <el-table-column label="姓名" prop="stuName" width="55" show-overflow-tooltip></el-table-column>
          <el-table-column label="类型" prop="typeName" show-overflow-tooltip></el-table-column>
          <el-table-column label="活动" prop="actName" show-overflow-tooltip></el-table-column>
          <el-table-column label="申请材料" prop="appData">
            <template #default="scope">
              <el-button type="warning" @click="viewAppData(scope.row.appData)">查看材料</el-button>
            </template>
          </el-table-column>
          <el-table-column label="提交时间" prop="createTime" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template #default="scope">
              <el-button type="primary" @click="handleView(scope.row)">初审</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 左侧分页区域 -->
      <div class="card02" style="background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
        <el-pagination @current-change="loadHistory" @size-change="loadHistory"
          v-model:current-page="historyData.pageNum" v-model:page-size="historyData.pageSize"
          :page-sizes="[8, 13, 18, 23]" layout="total, sizes, prev, pager, next, jumper" :total="historyData.total" />
      </div>
    </div>

    <!-- 右侧盒子 - 一周内时间数据 -->
    <div class="box">
      <h3 style="text-align: center; margin: 10px 0">近一周记录</h3>

      <!-- 右侧查询区域 -->
      <div class="card02"
        style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
        <el-input v-model="currentData.username" style="width: 200px; margin-right: 10px" placeholder="请输入姓名查询"
          disabled></el-input>
        <el-input v-model="currentData.realname" style="width: 200px; margin-right: 10px" placeholder="请选择类型查询"
          disabled></el-input>
        <el-button type="primary" @click="loadCurrent">查询</el-button>
        <el-button type="info" style="margin: 0 10px" @click="resetCurrent">重置</el-button>
      </div>

      <!-- 右侧数据表格区域 -->
      <div class="card"
        style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
        <el-table :data="currentData.tableData" stripe>
          <el-table-column label="姓名" prop="stuName" width="55" show-overflow-tooltip></el-table-column>
          <el-table-column label="类型" prop="typeName" show-overflow-tooltip></el-table-column>
          <el-table-column label="活动" prop="actName" show-overflow-tooltip></el-table-column>
          <el-table-column label="申请材料" prop="appData">
            <template #default="scope">
              <el-button type="warning" @click="viewAppData(scope.row.appData)">查看材料</el-button>
            </template>
          </el-table-column>
          <el-table-column label="提交时间" prop="createTime" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template #default="scope">
              <el-button type="primary" @click="handleView(scope.row)">初审</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 右侧分页区域 -->
      <div class="card02" style="background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
        <el-pagination @current-change="loadCurrent" @size-change="loadCurrent"
          v-model:current-page="currentData.pageNum" v-model:page-size="currentData.pageSize"
          :page-sizes="[8, 13, 18, 23]" layout="total, sizes, prev, pager, next, jumper" :total="currentData.total" />
      </div>
    </div>

    <el-dialog title="初审详情" v-model="viewVisible" width="800px" destroy-on-close>
      <el-descriptions column="1" border>
        <el-descriptions-item label="姓名">{{ viewForm.stuName }}</el-descriptions-item>
        <el-descriptions-item label="创新创业活动类型">{{ viewForm.typeName }}</el-descriptions-item>
        <el-descriptions-item label="创新创业活动项">{{ viewForm.actName }}</el-descriptions-item>
        <el-descriptions-item label="材料申请时间">{{ dateFormat(viewForm.createTime) }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button type="danger" @click="data.rejectVisible = true; rejectForm = {}">打回</el-button>
        <el-button type="primary" @click="viewVisible = false">关闭</el-button>
        <el-button type="success" @click="pass(viewForm.recordId, 3, viewForm.stuId)">通过</el-button>
      </template>
    </el-dialog>

    <el-dialog title="打回理由" v-model="data.rejectVisible" width="700px" destroy-on-close>
      <el-form :model="rejectForm" ref="formRef" :rules="data.rules" label-width="100px">
        <el-form-item prop="reason" label="理由(必填)" style="margin-right: 30px">
          <el-input type="textarea" :rows="4" v-model="rejectForm.reason"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="data.rejectVisible = false">取消</el-button>
        <el-button type="primary" @click="rejectPass(viewForm.recordId, 4, viewForm.stuId)">确认打回</el-button>
      </template>
    </el-dialog>

    <el-dialog title="查看材料详细" v-model="data.appDataViewVisible" width="70%" destroy-on-close>
      <div style="padding: 20px; max-height: 60vh; overflow-y: auto;">
        <!-- 文件类型切换标签 -->
        <div style="margin-bottom: 15px; display: flex; flex-wrap: wrap;">
          <el-tag v-for="(file, index) in data.appDataList" :key="index"
            :type="data.activeFileIndex === index ? 'primary' : 'warning'"
            style="margin: 0 10px 10px 0; cursor: pointer;" @click="data.activeFileIndex = index">
            {{ getFileName(file.url) }} ({{ file.type }})
          </el-tag>
        </div>

        <!-- 图片预览 -->
        <div v-if="data.appDataList[data.activeFileIndex]?.type === 'image'"
          style="display: flex; justify-content: center;">
          <el-image :src="data.appDataList[data.activeFileIndex].url" fit="contain"
            style="max-width: 100%; max-height: 500px;" :preview-src-list="data.imagePreviewList">
            <template #placeholder>
              <div style="text-align: center; padding: 20px;">
                <el-icon class="is-loading" style="font-size: 24px;">
                  <Loading />
                </el-icon>
              </div>
            </template>
            <template #error>
              <div class="image-error">
                <el-icon>
                  <Picture />
                </el-icon>
                <p>图片加载失败</p>
              </div>
            </template>
          </el-image>
        </div>

        <!-- PDF预览 -->
        <div v-else-if="data.appDataList[data.activeFileIndex]?.type === 'pdf'" class="preview-container">
          <div ref="pdfContainer" style="width: 100%; height: 100%;"></div>
        </div>

        <!-- Word预览 -->
        <div v-else-if="data.appDataList[data.activeFileIndex]?.type === 'word'" class="preview-container">
          <div ref="wordContainer" style="width: 100%; height: 100%;"></div>
        </div>

        <!-- 其他文件类型 -->
        <div v-else-if="!['image', 'pdf', 'word'].includes(data.appDataList[data.activeFileIndex]?.type)"
          class="preview-container preview-error">
          <el-icon>
            <Files />
          </el-icon>
          <p>不支持在线预览</p>
          <el-button type="primary" @click="downloadFile(data.appDataList[data.activeFileIndex].url)">
            下载文件
          </el-button>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="data.appDataViewVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch, nextTick } from 'vue';
import alovaInstance from "@/utils/request";
import { ElMessage, ElMessageBox } from 'element-plus';
import { dateFormat } from '@/utils/dateUtil';
import { firstChexk, firstRecord, addErrorMessage, addSuccessMessage } from '@/api/teacher/teacher';
import { renderAsync } from 'docx-preview';
import * as pdfjsLib from 'pdfjs-dist';
import 'pdfjs-dist/build/pdf.worker.entry';

// 定义响应式数据
const currentData = ref({
  username: '',
  realname: '',
  title: '',
  status: '',
  pageNum: 1,
  pageSize: 8,
  total: 0,
  tableData: [],
});

const data = reactive({
  user: JSON.parse(localStorage.getItem('credit-system-user') || '{}'),
  form: {},
  appDataViewVisible: false,
  // 新增：存储解析后的材料列表
  appDataList: [],
  activeFileIndex: 0,
  imagePreviewList: [],
  rules: {
    reason: [
      { required: true, message: '打回理由不能为空', trigger: 'blur' }
    ]
  },
  rejectVisible: false
})
const formRef = ref();

const historyData = ref({
  username: '',
  realname: '',
  title: '',
  status: '',
  pageNum: 1,
  pageSize: 8,
  total: 0,
  tableData: [],
});

const viewVisible = ref(false);
const viewForm = ref({});
/*const rejectVisible = ref(false);*/
const rejectForm = ref({
  reason: ''
});

// 文件类型映射
const fileTypeMap = {
  jpg: 'image',
  jpeg: 'image',
  png: 'image',
  gif: 'image',
  bmp: 'image',
  pdf: 'pdf',
  doc: 'word',
  docx: 'word'
};

// 在viewAppData方法中添加以下逻辑
const viewAppData = (appData) => {
  // 解析URL为数组
  const urlArray = appData.split(',');

  // 处理每个文件的类型
  data.appDataList = urlArray.map(url => {
    const extension = url.split('.').pop().toLowerCase();
    return {
      url,
      type: fileTypeMap[extension] || 'other',
      extension
    };
  });

  // 提取图片URL用于预览列表
  data.imagePreviewList = data.appDataList
    .filter(file => file.type === 'image')
    .map(file => file.url);
  // 默认激活第一个文件
  data.activeFileIndex = 0;
  // 打开对话框
  data.appDataViewVisible = true;
  // 等待DOM更新后渲染PDF/Word
  nextTick(() => {
    renderCurrentFile();
  });
};

// 添加文件渲染方法
const renderCurrentFile = () => {
  const file = data.appDataList[data.activeFileIndex];

  if (!file) return;

  // 清除之前渲染的内容
  if (pdfContainer.value) pdfContainer.value.innerHTML = '';
  if (wordContainer.value) wordContainer.value.innerHTML = '';

  switch (file.type) {
    case 'pdf':
      renderPDF(file.url);
      break;
    case 'word':
      renderWord(file.url);
      break;
  }
};

// 添加PDF渲染方法
const pdfContainer = ref(null);
const renderPDF = async (url) => {
  if (!pdfContainer.value) return;

  try {
    const loadingTask = pdfjsLib.getDocument(url);
    const pdf = await loadingTask.promise;

    // 清空容器
    pdfContainer.value.innerHTML = '';

    // 渲染第一页
    const page = await pdf.getPage(1);
    const viewport = page.getViewport({ scale: 1.5 });

    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    pdfContainer.value.appendChild(canvas);

    await page.render({
      canvasContext: context,
      viewport
    });
  } catch (error) {
    console.error('PDF渲染失败:', error);
    pdfContainer.value.innerHTML = '<p>PDF预览失败，请尝试下载查看</p>';
  }
};

// 添加Word渲染方法
const wordContainer = ref(null);
const renderWord = async (url) => {
  if (!wordContainer.value) return;

  try {
    // 获取Word文件
    const response = await fetch(url);
    const blob = await response.blob();
    // 给容器添加样式类
    wordContainer.value.className = 'word-preview-container';
    // 渲染Word文档
    await renderAsync(blob, wordContainer.value, null, {
      className: "docx", // 默认和文档样式类名
      inWrapper: true, // 启用包装器
      ignoreWidth: false,
      ignoreHeight: false,
      ignoreFonts: false,
      breakPages: true,
      debug: false,
      experimental: false,
      trimXmlDeclaration: true,
      useBase64URL: false,
      useMathMLPolyfill: false,
      showChanges: false,
    });
  } catch (error) {
    console.error('Word渲染失败:', error);
    wordContainer.value.innerHTML = '<p>Word预览失败，请尝试下载查看</p>';
  }
};

// 添加下载文件方法
const downloadFile = (url) => {
  const a = document.createElement('a');
  a.href = url;
  a.download = url.split('/').pop();
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

// 添加获取文件名方法
const getFileName = (url) => {
  const parts = url.split('/');
  return parts[parts.length - 1];
};

// 监听激活文件的变化
watch(() => data.activeFileIndex, () => {
  nextTick(renderCurrentFile);
});


// 加载近一周的数据
const loadCurrent = () => {
  alovaInstance.Get('/teacher/getFirst', {
    params: {
      teaId: data.user.teaId,
      page: currentData.value.pageNum,
      size: currentData.value.pageSize
    }
  }).then(res => {
    if (res.code === '200') {
      currentData.value.tableData = res.data?.list
      currentData.value.total = res.data?.total
    }
  }).catch(err => {
    ElMessage.error(err.message)
  })
};

// 重置当前时间查询条件
const resetCurrent = () => {
  currentData.value.username = '';
  currentData.value.realname = '';
  currentData.value.title = '';
  currentData.value.status = '';
  currentData.value.pageNum = 1;
};

// 加载一周前的数据
const loadHistory = () => {
  alovaInstance.Get('/teacher/getFirst2', {
    params: {
      teaId: data.user.teaId,
      page: historyData.value.pageNum,
      size: historyData.value.pageSize,
    }
  }).then(res => {
    if (res.code === '200') {
      historyData.value.tableData = res.data?.list
      historyData.value.total = res.data?.total
    }
  }).catch(err => {
    ElMessage.error(err.message)
  })
};

// 重置历史时间查询条件
const resetHistory = () => {
  historyData.value.username = '';
  historyData.value.realname = '';
  historyData.value.title = '';
  historyData.value.status = '';
  historyData.value.pageNum = 1;
};

// 查看详情
const handleView = (row) => {
  viewForm.value = { ...row };
  viewVisible.value = true;
};

// 组件挂载后加载数据
onMounted(() => {
  loadCurrent();
  loadHistory();
});

//教师初审通过
//初审通过时还要新增一条初审记录表
// 处理【通过】操作（无需校验打回表单）
const pass = (id, s, stuId) => {
  ElMessageBox.confirm(
    '此操作将提交初审通过，是否确认？',
    '确认提交',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    data.form.recordId = id;
    data.form.stuId = stuId
    data.form.teaId = data.user.teaId;
    data.form.reason = null;
    data.form.status = s;
    submitForm(); // 抽取通用提交逻辑
  }).catch(() => {
    ElMessage.warning('已取消操作');
  });
};

// 处理【打回】操作（需校验打回表单）
const rejectPass = (id, s, stuId) => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm(
        '此操作将提交初审打回，是否确认？',
        '确认打回',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        data.form.recordId = id;
        data.form.stuId = stuId;
        data.form.teaId = data.user.teaId;
        data.form.reason = rejectForm.value.reason;
        data.form.status = s;
        submitForm(); // 复用提交逻辑
        data.rejectVisible = false; // 关闭打回弹窗
      }).catch(() => {
        ElMessage.warning('已取消打回操作');
      });
    }
  });
};

// 通用提交逻辑（抽取重复代码）
const submitForm = () => {
  firstChexk(data.form).then((res) => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      // 1. 先执行新增终审记录
      firstRecord(data.form).then(() => {
        const stuId = Number(data.form.stuId);
        // 2. 判断是通过还是打回，调用对应的信息发送接口
        if (data.form.status == '3') {
          return addSuccessMessage(stuId, data.user.teaId);
        } else if (data.form.status == '4') {
          // 状态为 4 代表打回，调用发送打回信息接口
          return addErrorMessage(stuId, data.user.teaId);
        }
        return Promise.resolve(); // 既不是通过也不是打回，直接 resolve
      }).then(() => {
        // 3. 信息发送（如果有）成功后，刷新页面
        setTimeout(() => {
          location.reload();
        }, 500);
      }).catch(error => {
        console.error('信息发送失败:', error);
        ElMessage.error(error.message);
      });
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
  });
};

</script>

<style scoped>
.container {
  display: flex;
  gap: 20px;
  padding: 5px 10px;
}

.box {
  flex: 1;
}

.card {
  padding: 15px;
  box-sizing: border-box;
}

.card02 {
  padding: 10px 10px;
  box-sizing: border-box;
}

.ellipsis-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
}

::v-deep .el-descriptions-item__content {
  word-break: break-all;
  line-height: 1.6;
}

/* PDF 预览相关样式 */
.preview-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  background-color: #838382;
  min-height: 500px;
  padding: 60px 40px 60px 100px;
  /* 增加内边距，让内容不贴边 */
}

.word-preview-container {
  padding: 0px 100px 10px 40px;
  margin: 0 0 0 0;
}
</style>